package com.swak.persistence.mybatis.methods.impls;

import com.swak.define.ColumnDefine;
import com.swak.persistence.mybatis.methods.AbstractMethod;
import com.swak.persistence.mybatis.methods.Sqls;

/**
 * 通过违反唯一约束将插入变为 update；
 * 比较符合中间表的新增方式， 由于中间表通常将 DelAt 作为唯一键的一部分，所以需要在新增中添加此字段
 * 
 * @author 618lf
 */
@Deprecated
public class Replace extends AbstractMethod {

	@Override
	protected void doInject() {
		if (!this.table.define.useReplace()) {
			return;
		}
		String sql = new StringBuilder().append(SCRIPT_START).append(INSERT).append(SPACE).append(this.table.getName())
				.append(LEFT_BRACKET).append(this.parseSqlColumns()).append(RIGHT_BRACKET).append(SPACE).append(VALUES)
				.append(LEFT_BRACKET).append(this.parseInsertSqlProperty()).append(RIGHT_BRACKET).append(SPACE)
				.append(REPLACE).append(SPACE).append(UPDATE).append(SPACE).append(this.parseUpdateProperty())
				.append(PADDING2).append(SCRIPT_END).toString();

		this.addInsertMappedStatement(this.table.entity, Sqls.REPLACE.getMethod(), sql);
	}

	/**
	 * 解析列
	 */
	@Override
	protected String parseSqlColumns() {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : table.columns) {
			String name = column.name;
			sql.append(name).append(SPLIT);
		}
		sql.append(DEL_AT);
		return sql.toString();
	}

	/**
	 * insert 后面的属性值
	 * 
	 * @param <T>
	 * @param table
	 * @return
	 */
	protected String parseInsertSqlProperty() {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : table.columns) {
			String name = column.javaProperty;
			sql.append(HASH_LEFT_BRACE).append(name).append(RIGHT_BRACE).append(SPLIT);
		}
		sql.append(HASH_LEFT_BRACE).append(delAtProperty).append(RIGHT_BRACE);
		return sql.toString();
	}

	/**
	 * 解析修改列
	 */
	protected String parseUpdateProperty() {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : this.table.columns) {
			if (!column.isPk() && !column.isCreateDate()) {
				String name = column.name;
				String property = column.javaProperty;
				sql.append("<if test=\"").append(property).append(" != null\">").append(name).append(EQUALS)
						.append(HASH_LEFT_BRACE).append(property).append(RIGHT_BRACE).append(SPLIT).append("</if>");
			}
		}
		return sql.toString();
	}
}
